import {ipcRenderer} from 'electron'
import * as crypto from "crypto";
import child_process from "child_process";
import iconv from 'iconv-lite-electron'
import moment from "moment";
const algorithm = "aes-192-cbc";
const password = "djy2zxc";
const key = crypto.scryptSync(password, "salt", 24);
const iv = Buffer.alloc(16, 0); // Initialization vector.

export async function childSpawnPromise(command:string, args: string[]) {
  return new Promise<any>((resolve,reject)=>{
    const cmd = child_process.spawn(command, args, { shell: true})
    let datas = ''
    // 为了解决类型问题
    const icon = iconv as unknown as any
    cmd.stdout.on('data', (data: any) => {
      data = icon.decode(data, 'gbk')
      data = icon.encode(data, 'utf-8')
      datas += data
    });

    cmd.on('error', (data: any) => {
      reject(`执行命令发生错误:err:${data}, command:${command}`)
    });

    cmd.on('exit',(code: any, err)=>{
      console.log('exit code', code)
      console.log("err", err)
      resolve(datas)
    })
  })
}

export const newGame = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'
export const randomGame = 'rnbqkbnr/ppp1pppp/8/8/8/8/PP1PPP1P/R1BQK1NR w KQkq - 0 1'

export const emptyGame = '8/8/8/8/8/8/8/8 w - - 0 1'

export async function invoke(name: string, data:any) {
  return new Promise((resolve, reject)=> {
    try {
      ipcRenderer.invoke(name, data).then((res) => {
        resolve(res)
      })
    } catch(err) {
      reject(err)
    }
  })
}

export function existValue(str: any): boolean {
  return !(str === null || str === undefined);

}

export function getMD5(str: string): string {
  const md5 = crypto.createHash('md5').update(str).digest('hex');
  return md5.slice(0,16)
}

export async function sleep(ms=500): Promise<any> {
  return new Promise((resolve)=>{
    setTimeout(() => {
      resolve(null)
    }, ms);
  })
}
export function getCurrentTime(): string {
  return new Date().toLocaleString()
}

// 有些fen存了历史的棋步，计算md5会出现问题，所以要把这个数据去掉
// 如 rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/RNBQKBNR b KQkq e3 0 1
export function parseFenDropHistory(fen: string): string {
  let list = fen.split(' ')
  list[3] = '-'
  let res = ''
  for (const item of list){
    res += item
    res += ' '
  }
  res = res.slice(0, res.length - 1)
  return res
}


// aes加密
export function encrypt(str: string): string {
  const cipher = crypto.createCipheriv(algorithm, key, iv);

  let encrypted = cipher.update(str, "utf8", "hex");
  encrypted += cipher.final("hex");
  return encrypted
}

// aes解密
export function decrypt(str: string): string {
  const decipher = crypto.createDecipheriv(algorithm, key, iv);

  let decrypted = decipher.update(str, "hex", "utf8");
  decrypted += decipher.final("utf8");
  return decrypted
}

// 从数组随机选择一项
export function randomFromArray(arr: any[]): any {
  if (!arr.length) return null
  let randomIndex = Math.floor(Math.random() * arr.length);
  console.log("randomIndex", randomIndex)
  return arr[randomIndex];
}

// 检测字符串是否有特殊字符
export function checkIllegalText (str: string): boolean {
  if (str.indexOf('/') !== -1) return true
  if (str.indexOf('\\') !== -1) return true
  return false
}

// 字符串转16进制存储
export function str2hex(str: string): string {
  const buffer = Buffer.from(str, 'utf-8')
  return buffer.toString('hex')
}

// 16进制转字符串
export function hex2str(hex: string): string {
  return Buffer.from(hex, 'hex').toString()
}

// 数组转哈希表
export function arr2HashMap(arr: any[], key: string): {[key: string]: any} {
  if (!arr || !arr.length) return {}
  let map: any = {}
  for (const item of arr) {
    map[item[key]] = item
  }
  return map
}

// 去除多余的字符串 空格 双引号
export function replaceAndTrim(str: string, key: string): string {
  str = str.replaceAll(key, '')
  str = str.replaceAll('"', '')
  return str.trim()
}

export function safeJsonParse(str: string): any {
  try {
    return JSON.parse(str)
  } catch {
    return str
  }
}


export function getRandom(max: number, min=0): number {
  return crypto.randomInt(min, max)
}

export function getDateTextBySecond(second: number): string {
  let d = moment.duration(second, 'seconds');
  return d.hours() + '时' + d.minutes() + '分' + d.seconds() + '秒'
}

export function bless(): string {
  let bless =
    ' _______  __   __  _______  _______  _______  __   __  _______  _______  _______ \n' +
    '|       ||  | |  ||       ||       ||       ||  |_|  ||   _   ||       ||       |\n' +
    '|       ||  |_|  ||    ___||  _____||  _____||       ||  |_|  ||_     _||    ___|\n' +
    '|       ||       ||   |___ | |_____ | |_____ |       ||       |  |   |  |   |___ \n' +
    '|      _||       ||    ___||_____  ||_____  ||       ||       |  |   |  |    ___|\n' +
    '|     |_ |   _   ||   |___  _____| | _____| || ||_|| ||   _   |  |   |  |   |___ \n' +
    '|_______||__| |__||_______||_______||_______||_|   |_||__| |__|  |___|  |_______|'
  console.log(bless)
  return bless
}